package cn.kmia.hrm.service.system;

import cn.kmia.hrm.pojo.system.UserRole;
import cn.kmia.hrm.service.BaseService;
import org.apache.log4j.Logger;
import org.nutz.aop.interceptor.ioc.TransAop;
import org.nutz.dao.Sqls;
import org.nutz.dao.sql.Sql;
import org.nutz.ioc.aop.Aop;

import java.sql.Timestamp;
import java.util.Date;

/**
 * @项目：
 * @作者：4K
 * @描述：用户对应角色信息
 * @日期：created in 9:32 2018/3/5
 */
public class UserRoleService extends BaseService {

    private static Logger log = Logger.getLogger(UserRoleService.class);

    /**
     * 设置
     *
     * @param userRoles UserRole[] 角色用户对应信息
     * @param idcard    String  操作人
     * @return
     */
    @Aop(TransAop.READ_COMMITTED)
    public void edit(UserRole[] userRoles, String idcard) throws Exception {
        if (userRoles != null) {
            try {
                String userIds = "";
                for (UserRole userRole : userRoles) {
                    userIds += "," + userRole.getUserId();
                }
                // 删除原有用户角色
                if (!userIds.equals("")) {
                    userIds = userIds.substring(1);
                    Sql sql = Sqls.create("delete from sys_user_role where user_id in (" + userIds + ")");
                    dao.execute(sql);
                }
                // 新增用户角色
                for (int i = 0; i < userRoles.length; i++) {
                    userRoles[i].setOpBy(idcard);
                    userRoles[i].setUpdateTime(new Timestamp(new Date().getTime()));
                    userRoles[i].setCreateTime(new Timestamp(new Date().getTime()));
                    dao.insert(userRoles[i]);
                }
            } catch (Exception e) {
                log.error("新增角色用户对应关系失败", e);
                throw e;
            }
        }
    }

    /**
     * 删除
     *
     * @param userIds 用户IDs
     * @return
     */
    public void delete(String userIds) throws Exception {
        if (userIds != null) {
            try {
                Sql sql = Sqls.create("delete from sys_user_role where user_id in (" + userIds + ")");
                dao.execute(sql);
            } catch (Exception e) {
                log.error("删除用户对应角色异常", e);
                throw e;
            }
        }

    }
}
